<template>
  <div class="container-fluid">
    <!-- 顶部导航栏 -->
    <header class="col-md-12 bg-primary text-white p-3">
      <div class="row align-items-center">
        <div class="col-auto">
          <h1>停车场管理系统</h1>
        </div>
        <div class="col"></div>
        <div class="col-auto text-right">
          <span>{{ username }}</span>
          <router-link to="/" class="btn btn-light ml-2">返回首页</router-link>
          <button @click="logout" class="btn btn-light ml-2">退出</button>
        </div>
      </div>
    </header>

    <!-- 主内容区域 -->
    <main class="col-md-12 mt-4">
      <div class="card">
        <div class="card-header bg-secondary text-white">
          <div class="row align-items-center">
            <div class="col-auto">
              <h2>固定车主管理</h2>
            </div>
            <div class="col">
              <!-- 空列，用于占据中间空间 -->
            </div>
            <div class="col-auto">
              <button @click="addFixedOwner" class="btn btn-primary">添加固定车辆</button>
            </div>
          </div>
        </div>
        <div class="card-body">
          <!-- 搜索区域 -->
          <div class="mb-4 p-3 bg-light rounded">
            <div class="row">
              <div class="col-md-4 mb-2">
                <label for="plateNumberSearch" class="form-label">车牌号</label>
                <input type="text" id="plateNumberSearch" v-model="searchForm.plateNumber" class="form-control" placeholder="请输入车牌号" @input="searchFixedOwners">
              </div>
              <div class="col-md-4 mb-2">
                <label for="ownerNameSearch" class="form-label">车主姓名</label>
                <input type="text" id="ownerNameSearch" v-model="searchForm.ownerName" class="form-control" placeholder="请输入车主姓名" @input="searchFixedOwners">
              </div>
              <div class="col-md-4 mb-2">
                <label for="statusSearch" class="form-label">状态</label>
                <select id="statusSearch" v-model="searchForm.status" class="form-control" @change="searchFixedOwners">
                  <option value="">全部</option>
                  <option value="0">正常</option>
                  <option value="1">过期</option>
                </select>
              </div>
            </div>
          </div>
          
          <table class="table table-bordered">
            <thead>
              <tr>
                <th>序号</th>
                <th>车牌号</th>
                <th>车辆类型</th>
                <th>车主姓名</th>
                <th>联系电话</th>
                <th>开始日期</th>
                <th>结束日期</th>
                <th>状态</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(owner, index) in fixedOwners" :key="owner.id">
                <td>{{ index + 1 }}</td>
                <td>{{ owner.plateNumber }}</td>
                <td>{{ this.formatVehicleType(owner.vehicleType) }}</td>
                <td>{{ owner.ownerName }}</td>
                <td>{{ owner.phone }}</td>
                <td>{{ owner.startDate }}</td>
                <td>{{ owner.endDate }}</td>
                <td>
                  <span :class="{
                    'text-success': owner.status === 0,
                    'text-danger': owner.status === 1
                  }">
                    {{ owner.status === 0 ? '正常' : '过期' }}
                  </span>
                </td>
                <td>
                  <button @click="editFixedOwner(owner.id)" class="btn btn-info btn-sm mr-2">编辑</button>
                  <button @click="renewContract(owner.id)" class="btn btn-success btn-sm mr-2">续约</button>
                  <button @click="deleteFixedOwner(owner.id)" class="btn btn-danger btn-sm">删除</button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </main>
  </div>
</template>

<script>
import axios from '@/utils/axios'
export default {
  name: 'FixedManageView',
  data() {
    return {
      username: '',
      fixedOwners: [],
      originalFixedOwners: [], // 存储原始数据用于重置搜索
      searchForm: {
        plateNumber: '',
        ownerName: '',
        status: ''
      }
    }
  },
  mounted() {
    this.username = localStorage.getItem('username') || '管理员'
    this.loadFixedOwners()
  },
  methods: {
    logout() {
      localStorage.removeItem('isLoggedIn')
      localStorage.removeItem('username')
      this.$router.push('/login')
    },
    
    loadFixedOwners() {
      // 调用后端API获取固定车辆列表
      axios.get('/fixed-manage/list', {
        params: {
          pageNum: 1,  // 从第1页开始
          pageSize: 100,  // 一次性获取足够多的数据用于前端展示
          plateNumber: this.searchForm.plateNumber || undefined,
          ownerName: this.searchForm.ownerName || undefined,
          status: this.searchForm.status || undefined
        }
      })
        .then(response => {
          // 由于axios响应拦截器直接返回了response.data
          let data = response || {};
          
          // 处理后端返回的PageInfo<FixedManageVo>类型数据
          // PageInfo包含list属性，其中包含实际的车辆数据列表
          if (data && data.list && Array.isArray(data.list)) {
            this.fixedOwners = data.list.map(item => ({
              id: item.id,
              plateNumber: item.plateNumber || '未知',
              vehicleType: item.type,  // 后端的type对应前端的vehicleType
              ownerName: item.ownerName || '未知',
              phone: item.phone || '未提供',
              startDate: item.createdAt ? new Date(item.createdAt).toLocaleDateString('zh-CN') : '',  // 后端的createdAt对应前端的startDate
              endDate: item.updatedAt ? new Date(item.updatedAt).toLocaleDateString('zh-CN') : '',  // 后端的updatedAt对应前端的endDate
              status: item.status  // 后端的status值
            }))
            
            // 保存原始数据用于重置搜索
            this.originalFixedOwners = JSON.parse(JSON.stringify(this.fixedOwners));
            
            console.log('获取固定车辆数据成功:', this.fixedOwners);
          } else {
            console.warn('返回的数据格式不符合预期，应为PageInfo类型');
            this.fixedOwners = [];
            this.originalFixedOwners = [];
          }
        })
        .catch(error => {
          console.error('获取固定车辆列表失败:', error);
          // 错误处理：保持fixedOwners为空数组
          this.fixedOwners = [];
          this.originalFixedOwners = [];
        });
      },
      
      // 搜索功能
      searchFixedOwners() {
        // 直接重新调用API获取数据，使用最新的搜索条件
        this.loadFixedOwners();
      
      // 根据搜索条件过滤数据
      this.fixedOwners = this.originalFixedOwners.filter(owner => {
        let matchPlateNumber = true;
        let matchOwnerName = true;
        let matchStatus = true;
        
        // 车牌号搜索
        if (this.searchForm.plateNumber) {
          matchPlateNumber = owner.plateNumber.toLowerCase().includes(this.searchForm.plateNumber.toLowerCase());
        }
        
        // 车主姓名搜索
        if (this.searchForm.ownerName) {
          matchOwnerName = owner.ownerName.toLowerCase().includes(this.searchForm.ownerName.toLowerCase());
        }
        
        // 状态搜索
        if (this.searchForm.status !== '') {
          // 仅支持状态0（正常）和1（过期）的搜索
          const searchStatus = parseInt(this.searchForm.status);
          if (searchStatus === 0 || searchStatus === 1) {
            matchStatus = owner.status === searchStatus;
          }
        }
        
        return matchPlateNumber && matchOwnerName && matchStatus;
      });
    },
    
    // 格式化车辆类型显示
    formatVehicleType(type) {
      // 转换为数字类型进行比较
      const typeNum = Number(type);
      
      switch(typeNum) {
        case 0:
          return '临时车';
        case 1:
          return '月租车';
        case 2:
          return '年租车';
        default:
          return '未知';
      }
    },
    
    addFixedOwner() {
      // 添加固定车主逻辑
      alert('添加固定车主功能待实现')
    },
    
    editFixedOwner(id) {
      // 编辑固定车主逻辑
      alert(`编辑固定车主 ${id}`)
    },
    
    renewContract(id) {
      // 续约逻辑
      if (confirm('确定要为该固定车主续约吗？')) {
        const owner = this.fixedOwners.find(o => o.id === id)
        if (owner) {
          // 简单模拟续约一年
          const currentYear = new Date().getFullYear()
          owner.validUntil = `${currentYear + 1}-12-31`
          owner.status = 0
          alert('续约成功')
        }
      }
    },
    
    deleteFixedOwner(id) {
      // 删除固定车主逻辑
      if (confirm('确定要删除这个固定车主吗？')) {
        this.fixedOwners = this.fixedOwners.filter(owner => owner.id !== id)
        alert('删除成功')
      }
    }
  }
}
</script>

<style >
/* 这里可以添加组件特定的样式 */
</style>